package com.example.apple.hxbtc.activity;

import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.apple.hxbtc.R;
import com.example.apple.hxbtc.chart.KChartAdapter;
import com.example.apple.hxbtc.chart.KChartView;
import com.example.apple.hxbtc.chart.KLineEntity;
import com.example.apple.hxbtc.helper.DataHelper;
import com.github.tifezh.kchartlib.chart.formatter.DateFormatter;
import com.github.tifezh.kchartlib.chart.impl.IKChartView;
import com.github.tifezh.kchartlib.utils.TimeUtils;
import com.github.tifezh.kchartlib.utils.ViewUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;


/**
 * Created by hpz on 17/2/22.
 */

public class KlineActivity extends Activity {

    private ImageView imageView;

    private Button back_kline;

    private LinearLayout mLinearLayout;
    private KChartView mKChartView;

    private String[] titles = new String[]{"1分", "5分", "20分", "30分","45分", "1时", "1.5时", "6时h","1天", "1周", "2周"};

    private KChartAdapter mAdapter;

    List<KLineEntity> listBean = new ArrayList<>();

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            if (msg.what == 1) {
                //List<KLineEntity> kLineEntities = (List<KLineEntity>) msg.obj;
                mKChartView.startAnimation();
            }
            super.handleMessage(msg);
        }
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.avtivity_kine);
        //setTitle("OKCoin的K线图");
        TabLayout tablayout = (TabLayout) findViewById(R.id.table_kine);
        back_kline = (Button) findViewById(R.id.back_kline);
        back_kline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mLinearLayout = (LinearLayout) findViewById(R.id.ll_status);
        mKChartView = (KChartView) findViewById(R.id.kchart_view);
        imageView = (ImageView) findViewById(R.id.img_btn);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(KlineActivity.this,"你点击了按钮~",Toast.LENGTH_LONG).show();

            }
        });

        mAdapter = new KChartAdapter();
        mKChartView.setAdapter(mAdapter);
        mKChartView.setDateTimeFormatter(new DateFormatter());
        mKChartView.setGridRows(4);
        mKChartView.setGridColumns(4);
        mKChartView.setOnSelectedChangedListener(new IKChartView.OnSelectedChangedListener() {
            @Override
            public void onSelectedChanged(IKChartView view, Object point, int index) {
                KLineEntity data = (KLineEntity) point;
                Log.i("onSelectedChanged", "index:" + index + " closePrice:" + data.getClosePrice());
            }
        });
        mKChartView.setOverScrollRange(ViewUtil.Dp2Px(this, 100));

        tablayout.addTab(tablayout.newTab().setText(titles[0]));
        tablayout.addTab(tablayout.newTab().setText(titles[1]));
        tablayout.addTab(tablayout.newTab().setText(titles[2]));
        tablayout.addTab(tablayout.newTab().setText(titles[3]));
        tablayout.addTab(tablayout.newTab().setText(titles[4]));
        tablayout.addTab(tablayout.newTab().setText(titles[5]));
        tablayout.addTab(tablayout.newTab().setText(titles[6]));
        tablayout.addTab(tablayout.newTab().setText(titles[7]));
        tablayout.addTab(tablayout.newTab().setText(titles[8]));
        tablayout.addTab(tablayout.newTab().setText(titles[9]));
        tablayout.addTab(tablayout.newTab().setText(titles[10]));
        //tablayout.setTabTextColors(getResources().getColor(R.color.white), Color.BLACK);
        tablayout.setTabTextColors(getResources().getColor(R.color.dark_white), Color.WHITE);



        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        //initData();
        initGetData();
    }

    private void initGetData() {
        OkHttpUtils.get()
                .url("https://www.okcoin.cn/api/v1/kline.do?symbol=btc_cny&type=12hour")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {

                        if (!TextUtils.isEmpty(response)) {
                            try {
                                JSONArray jsonArray = new JSONArray(response);
                                KLineEntity klineBean;
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONArray jsonArray1 = (JSONArray) jsonArray.get(i);
                                    klineBean = new KLineEntity();
                                    for (int j = 0; j < jsonArray1.length(); j++) {
                                        long date = (long) jsonArray1.getDouble(0);
                                        String s = TimeUtils.millis2String(date);
                                        //Log.e("TAG---,timer--:",s+"\n");
                                        String[] splitStr = s.split(" ");
                                        Log.e("TAG----:", splitStr[0] + "\n");
                                        klineBean.Date = (splitStr[0]);
                                        klineBean.Open = (float) jsonArray1.getDouble(1);
                                        klineBean.High = (float) jsonArray1.getDouble(2);
                                        klineBean.Low = (float) jsonArray1.getDouble(3);
                                        klineBean.Close = (float) jsonArray1.getDouble(4);
                                        klineBean.dea = (float) jsonArray1.getDouble(5);
                                    }
                                    listBean.add(klineBean);
                                    //DataHelper.calculate(listBean);
                                }

                                //processingData();
                                DataHelper.calculate(listBean);
                                mAdapter.addFooterData(listBean);
                                //mAdapter.notifyDataSetChanged();

                                Message message = new Message();
                                message.what = 1;
                                // message.obj = listBean;
                                mHandler.sendMessage(message);

                            } catch (JSONException e) {

                            }
                        }

                    }
                });
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mLinearLayout.setVisibility(View.GONE);
            mKChartView.setGridRows(3);
            mKChartView.setGridColumns(8);
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            mLinearLayout.setVisibility(View.VISIBLE);
            mKChartView.setGridRows(4);
            mKChartView.setGridColumns(4);
        }
    }

}
